package com.advert.presentation.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.ConverterException;

public class EmailConverter extends ConverterBase {
    private final String EMAIL_PATTERN = "(\\w+.*\\w+)@(\\w+|(\\w+-\\w+)|(\\w+\\.\\w+))\\.\\w{1,3}";

    @Override
    protected Object convertToObject(FacesContext facesContext, UIComponent uiComponent, String s) {
        Object retVal = s;
        if (s.equals("")) {
            retVal = null;
        } else if (!s.matches(EMAIL_PATTERN)) {
            throw new ConverterException(buildConversionErrorMessage("EMAIL_FORMAT_INCORRECT"));
        }
        return retVal;
    }

    @Override
    protected String convertToString(FacesContext facesContext, UIComponent uiComponent, Object o) {
        String retVal = null;
        if (o != null) {
            retVal = o.toString();
        }
        return retVal;
    }
}
